import React, { Component } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { LZFormItem } from '@/components/LZForm'
import {
  Table,
  Card,
  message,
  Button,
  Form,
  Divider,
  Popconfirm,
  Tabs,
  Badge,
  Upload,
  Select,
  Icon,
  Modal,
  Input,
  Radio
} from 'antd'
import MyPageTable from '@/components/MyPageTable'
import { onTableData, getParam } from '@/utils/utils.js'
import ActivityMaterialsServices from './services'
import { uploadUrl } from '@/config/index'
import { getToken } from '@/utils/localStorage'
import moment from 'moment'
const { TabPane } = Tabs
const { Option } = Select
@Form.create()
export default class ActivityMaterials extends Component {
  state = {
    Key: '01',
    list: [],
    total: 1,
    loading: true,
    current: 1,
    tabPaneList: [
      {
        key: '01',
        content: '主题头图'
      },
      {
        key: '02',
        content: '豆腐块'
      },
      {
        key: '03',
        content: '轮播图'
      },
      {
        key: '04',
        content: '查看更多'
      },
      {
        key: '05',
        content: '搜索引导'
      },
      {
        key: '06',
        content: '品牌背书'
      }
    ],
    title: '',
    visible: false,
    fileList: [],
    imgSrc: '',
    imgVisible: false,
    data: {}
  }
  componentDidMount() {
    this.onQuery(1, 10)
  }
  onQuery = (pageNumber, pageSize) => {
    this.setState(
      {
        loading: true
      },
      () => {
        ActivityMaterialsServices.queryActivityConfigMaterialPage({
          pageNumber,
          pageSize,
          materialType: this.state.Key
        }).then(res => {
          this.setState({
            list: res.records,
            total: res.total,
            loading: false,
            current: res.current
          })
        })
      }
    )
  }
  onTabChange = e => {
    this.setState(
      {
        Key: e,
        current: 1
      },
      () => {
        this.onQuery(1, 10)
      }
    )
  }
  // 上传的回调
  handleUploadChange = ({ file, fileList, event }) => {
    const filelist = [...fileList] || []
    if (file.status === 'done') {
      filelist.map(item => {
        const imgSrc = item.response.data
        if (!imgSrc) {
          message.error('上传失败，token失效')
        } else {
          this.setState({
            imgSrc
          })
        }
      })
    }
    this.setState({
      fileList
    })
  }
  // 上传后删除的回调
  onRemove = () => {
    this.setState({
      fileList: [],
      imgSrc: ''
    })
  }
  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true
    })
  }
  edit = e => {
    const fileList = [
      {
        uid: 1,
        url: e.materialImage
      }
    ]
    this.setState({
      visible: true,
      title: '修改',
      fileList,
      data: e
    })
  }
  handleOk = e => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (this.state.title === '新增') {
          ActivityMaterialsServices.addActivityConfigMaterial({
            ...values,
            materialImage: this.state.imgSrc,
            materialType: this.state.Key
          }).then(res => {
            this.setState(
              {
                visible: false
              },
              () => {
                message.success('新增成功。')
                this.onQuery(1, 10)
              }
            )
          })
        } else {
          ActivityMaterialsServices.modifyActivityConfigMaterial({
            ...values,
            materialImage: this.state.imgSrc,
            materialType: this.state.Key,
            id: this.state.data.id
          }).then(res => {
            this.setState(
              {
                visible: false
              },
              () => {
                message.success('修改成功。')
                this.onQuery(this.state.current, 10)
              }
            )
          })
        }
      }
    })
  }
  deleteItem = e => {
    ActivityMaterialsServices.modifyActivityConfigMaterial({
      id: e.id,
      materialType: this.state.Key,
      deleteTime: moment().format('YYYY-MM-DD h:mm:ss')
    }).then(res => {
      message.success('删除成功。')
      this.onQuery(this.state.current, 10)
    })
  }
  onPage = e => {
    this.setState(
      {
        current: e.current
      },
      () => {
        this.onQuery(e.current, 10)
      }
    )
  }
  render() {
    const {
      Key,
      list,
      current,
      total,
      loading,
      tabPaneList,
      title,
      visible,
      fileList,
      imgSrc,
      imgVisible,
      data
    } = this.state

    const { getFieldDecorator } = this.props.form
    const paginationProps = {
      current: current,
      pageSize: 10,
      total,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      )
    }
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传照片</div>
      </div>
    )

    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        align: 'center'
      },
      {
        title: '名称',
        dataIndex: 'materialName',
        align: 'center'
      },
      {
        title: '图片',
        dataIndex: 'materialImage',
        align: 'center',
        render: e => (
          <img
            src={e}
            alt="e"
            style={{
              width: 125
            }}
          />
        )
      },
      {
        title: '跳转链接',
        dataIndex: 'jumpUrl',
        align: 'center',
        key: 'jumpUrl',
        width: 200
      },

      {
        title: '上线时间',
        dataIndex: 'createTime',
        align: 'center',
        key: 'createTime'
      },

      {
        title: '状态',
        dataIndex: 'status',
        align: 'center',
        key: 'status',
        render: text => {
          const success = text
          const status = success === '01' ? 'success' : 'default'
          const badgeText = success ? '有效' : '失效'
          return <Badge status={status} text={badgeText} />
        }
      },

      {
        title: '操作',
        align: 'center',
        key: 'action',
        render: (text, record) => (
          <div className="table-action">
            <a onClick={() => this.edit(record)}>修改</a>
            <Divider type="vertical" />
            <Popconfirm
              title="确定要删除吗？"
              onConfirm={() => this.deleteItem(record)}
            >
              <a>删除</a>
            </Popconfirm>
          </div>
        )
      }
    ]
    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Tabs
            activeKey={Key}
            animated={false}
            onChange={this.onTabChange}
            tabBarExtraContent={
              <div>
                <Button
                  type="primary"
                  onClick={() =>
                    this.setState({
                      visible: true,
                      title: '新增',
                      data: {},
                      fileList: []
                    })
                  }
                >
                  新增
                </Button>
              </div>
            }
          >
            {tabPaneList.map(item => {
              return (
                <TabPane tab={item.content} key={item.key}>
                  <Table
                    //   scroll
                    //   onPage={this.onPage}
                    onChange={this.onPage}
                    loading={loading}
                    pagination={paginationProps}
                    dataSource={onTableData(list)}
                    columns={columns}
                  />
                </TabPane>
              )
            })}
          </Tabs>
        </Card>
        {/* 新增 */}
        <Modal
          title={title}
          visible={visible}
          onOk={this.handleOk}
          //   confirmLoading={confirmLoading}
          destroyOnClose
          onCancel={() => {
            this.setState({
              visible: false,
              currentInfo: {},
              fileList: [],
              imgSrc: ''
            })
          }}
        >
          <Form {...formItemLayout}>
            <Form.Item label={`名称`}>
              {getFieldDecorator('materialName', {
                rules: [
                  {
                    required: true,
                    message: `名称不能为空`
                  }
                ],
                initialValue: data && data.materialName
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="跳转地址">
              {getFieldDecorator('jumpUrl', {
                rules: [
                  {
                    required: true,
                    message: '跳转地址不能为空'
                  }
                ],
                initialValue: data && data.jumpUrl
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <LZFormItem
              label="状态"
              field="status"
              required
              getFieldDecorator={getFieldDecorator}
              initialValue={(data && data.status) || '01'}
            >
              <Radio.Group>
                <Radio value={'01'}>有效</Radio>
                <Radio value={'00'}>无效</Radio>
              </Radio.Group>
            </LZFormItem>
            <Form.Item label="图片" required>
              {getFieldDecorator('materialImage', {
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      if (!imgSrc && !value) {
                        callback('图片不能为空')
                      }
                      callback()
                    }
                  }
                ],
                initialValue: imgSrc || (data && data.materialImage)
              })(
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  listType="picture-card"
                  fileList={fileList}
                  headers={{
                    token: getToken()
                  }}
                  onPreview={this.handlePreview} // 预览
                  onRemove={this.onRemove} // 删除
                  onDownload={this.onDownload}
                  onChange={this.handleUploadChange}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
              )}
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          visible={imgVisible}
          footer={null}
          onCancel={() => this.setState({ imgVisible: false })}
          width={600}
        >
          <img
            src={imgSrc || data.materialImage}
            alt=""
            className="preview-img"
          />
        </Modal>
      </PageHeaderWrapper>
    )
  }
}
